package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.domain.ClimbingPriceComparisonData;
import com.ruoyi.system.domain.ShopClassProductDetail;
import com.ruoyi.system.domain.vo.TreeNode;
import com.ruoyi.system.mapper.ClimbingPriceComparisonDataMapper;
import com.ruoyi.system.service.CategoryPriceService;
import com.ruoyi.system.service.ShopClassProductDetailService;
import org.apache.commons.collections4.iterators.CollatingIterator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/***
 * 说明
 * @author:ZZ
 * @date: 2024-12-03  14:54
 **/
@Service
public class CategoryPriceServiceImpl extends ServiceImpl<ClimbingPriceComparisonDataMapper, ClimbingPriceComparisonData> implements CategoryPriceService {

    @Autowired
    private ClimbingPriceComparisonDataMapper mapper;


    @Autowired
    private ShopClassProductDetailService shopClassProductDetailService;


    @Override
    public Object getTreeNodelist() {
        List<TreeNode> treeNodelist = mapper.getTreeNodelist();
//        TreeNode root = buildTree(treeNodelist);
        return treeNodelist;
    }

    @Override
    public Object getPriceOrBrandDetailList(String minPrice, String maxPrice, String brand, String className) {
        HashMap<Object, Object> map = new HashMap<>();
        QueryWrapper<ShopClassProductDetail> wrapper = new QueryWrapper<>();
        if (minPrice.equals(maxPrice)) {  //最大最小一样金额  默认为金额条件到了最大值
            wrapper.gt("price", maxPrice);
        } else {
            wrapper.between("price", minPrice, maxPrice);
        }
        wrapper.like(null != className && !className.isEmpty(), "class_name", className);
        List<ShopClassProductDetail> resultList = shopClassProductDetailService.list(wrapper);

//        List<ClimbingPriceComparisonData> resultList = mapper.getBrandList(className,minPrice,maxPrice);  //品牌商品
        map.put("Result", resultList);  //品牌商品
        SearchShoupItemCountuTIL(resultList);//批量修改搜索数量
        // 获取热门产品信息
        List<ClimbingPriceComparisonData> popularProductsList = mapper.getMaxNumberSearchesList();
        map.put("PopularProducts", popularProductsList);
        return map;
    }

    @Override
    public Object getProductNameSearch(String name) {
        HashMap<Object, Object> map = new HashMap<>();
        QueryWrapper<ShopClassProductDetail> wrapper = new QueryWrapper<>();
        wrapper.like("title", name);
//        List<ClimbingPriceComparisonData> resultList = mapper.selectList(wrapper); //根据名称模糊结果
        List<ShopClassProductDetail> resultList = shopClassProductDetailService.list(wrapper);
        map.put("Result", resultList);
        SearchShoupItemCountuTIL(resultList);//批量修改搜索数量
        // 获取热门产品信息
//        List<ClimbingPriceComparisonData> popularProductsList = mapper.getMaxNumberSearchesList();
        wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("number_searches");
        List<ShopClassProductDetail> popularProductsList = shopClassProductDetailService.list(wrapper);
        List<ShopClassProductDetail> firstEight = popularProductsList.subList(0, Math.min(8, popularProductsList.size()));
        //只获取前八个
        map.put("PopularProducts", firstEight);
        return map;
    }


    @Override
    public Object getProductDetailById(String id) {
//        QueryWrapper<ClimbingPriceComparisonData> wrapper = new QueryWrapper<>();
//        wrapper.like("id", id);
//        ClimbingPriceComparisonData  comparisonData = mapper.selectOne(wrapper); //根据名称模糊结果
        QueryWrapper<ShopClassProductDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
//        List<ClimbingPriceComparisonData> resultList = mapper.selectList(wrapper); //根据名称模糊结果
        ShopClassProductDetail detail = shopClassProductDetailService.getOne(wrapper);
        return detail;
    }


    @Override
    public Object getProductClassById(String id) {
        List<ClimbingPriceComparisonData> result = new ArrayList<>();
        QueryWrapper<ClimbingPriceComparisonData> wrapper = new QueryWrapper<>();
//        wrapper.eq("category_id",id);
//        ClimbingPriceComparisonData comparisonData1 = mapper.selectOne(wrapper);//根据名称模糊结果
//        result.add(comparisonData1);
        wrapper.eq("category_id", id);
        List<ClimbingPriceComparisonData> comparisonData = mapper.selectList(wrapper); //根据名称模糊结果
        if (null != comparisonData && comparisonData.size() == 1) {
            if (comparisonData.get(0).getPid() == 0) {
                result.add(comparisonData.get(0));
                return result;
            }
        }
        if (null != comparisonData && comparisonData.size() >= 2) {
            result.add(comparisonData.get(0));
            GetAncestors(result, comparisonData.get(0).getPid());
        }
        return result;
    }


    /**
     * 根据指定类名的pid获取上级分类信息，并将获取到的信息放入指定集合中。
     *
     * @param categories 所有分类的列表
     */
    public void GetAncestors(List<ClimbingPriceComparisonData> categories, Integer pid) {
        // 根据当前节点的pID获取上级分类名称信息
        QueryWrapper<ClimbingPriceComparisonData> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id", pid);
        ClimbingPriceComparisonData comparisonData = mapper.selectOne(wrapper); //根据名称模糊结果
        if (!comparisonData.getPid().equals(0)) {
            categories.add(comparisonData);
            GetAncestors(categories, comparisonData.getPid());
        } else {
            categories.add(comparisonData);
        }
    }

    /**
     * 根据id查找分类
     *
     * @param categories 所有分类的列表
     * @param id         分类的id
     * @return 找到的分类，如果没有找到返回null
     */
    private ClimbingPriceComparisonData findCategoryById(List<ClimbingPriceComparisonData> categories, String id) {
        for (ClimbingPriceComparisonData category : categories) {
            if (category.getCategoryId() == id) {
                return category;
            }
        }
        return null;
    }


    public void SearchShoupItemCountuTIL(List<ShopClassProductDetail> resultList) {
        if (resultList != null && resultList.size() > 0) {
//            for (ClimbingPriceComparisonData comparisonData : resultList) {
            shopClassProductDetailService.updateBatchById(resultList);
//            }
        }
    }


    public void SearchItemCountuTIL(List<ClimbingPriceComparisonData> resultList) {
        if (resultList != null && resultList.size() > 0) {
//            for (ClimbingPriceComparisonData comparisonData : resultList) {
            mapper.updateByDetail(resultList);
//            }
        }
    }

    @Override
    public Object getSeeAllByClick(String categoryId, Integer pageSize, Integer pageNum) {
        HashMap<Object, Object> map = new HashMap<>();
        QueryWrapper<ClimbingPriceComparisonData> wrapper = new QueryWrapper<>();
        wrapper.like("pid", categoryId);
        List<ClimbingPriceComparisonData> resultList = mapper.selectList(wrapper); //根据名称模糊结果
        // 假设resultList是你的数据列表
        List<ClimbingPriceComparisonData> page = getPage(resultList, pageNum, pageSize);
        map.put("Result", page);
        SearchItemCountuTIL(resultList);//批量修改搜索数量
        // 获取热门产品信息
        List<ClimbingPriceComparisonData> popularProductsList = mapper.getMaxNumberSearchesList();
        map.put("PopularProducts", popularProductsList);
        // 相关商品页
        map.put("RelatedGoods", new ArrayList<>());
        return map;
    }

    public static <T> List<T> getPage(List<T> list, int pageNumber, int pageSize) {
        int fromIndex = (pageNumber - 1) * pageSize;
        int toIndex = pageNumber * pageSize;
        return list.subList(fromIndex, Math.min(toIndex, list.size()));
    }


    @Override
    public Object getHomeProductDisplayList() {
        List<ClimbingPriceComparisonData> resultList = new ArrayList<>();
        QueryWrapper<ClimbingPriceComparisonData> wrapper = new QueryWrapper<>();
        wrapper.eq("pid", 0);
        wrapper.orderByDesc("create_time");
        List<ClimbingPriceComparisonData> list = mapper.selectList(wrapper); //获取一级分类 集合
        if (null != list && list.size() > 0) {  //一级
            //随机从一级分类集合中获取一个对象  放入结果集合
            ClimbingPriceComparisonData randomElement = getRandomElement(list);
            resultList.add(randomElement);
        }
        wrapper = new QueryWrapper<>();
        wrapper.gt("level", 1);
        wrapper.orderByDesc("create_time");
        list = mapper.selectList(wrapper); //获取一级分类 集合
        if (null != list && list.size() > 0) {  //一级之外所有
            Map<Integer, List<ClimbingPriceComparisonData>> groupedByAge = list.stream().collect(Collectors.groupingBy(ClimbingPriceComparisonData::getLevel));
//            Set<Integer> keys = groupedByAge.keySet();
            if (null != groupedByAge && groupedByAge.size() > 0) {
                // 二 级
                resultList.add(getRandomElement(groupedByAge.get(2)));
                // 三 级
                resultList.add(getRandomElement(groupedByAge.get(3)));
                // 四 级
                resultList.add(getRandomElement(groupedByAge.get(4)));
                // 五 级
                resultList.add(getRandomElement(groupedByAge.get(5)));
            }

        }
        //获取对应商品集合
        for (ClimbingPriceComparisonData climbingPriceComparisonData : resultList) {
            wrapper = new QueryWrapper<>();
            wrapper.eq("level", climbingPriceComparisonData.getLevel());
            wrapper.orderByDesc("create_time");
            list = mapper.selectList(wrapper); //获取一级分类 集合
            //获取集合中随机 6个商品信息
            if (null != list && list.size() <= 6) {
                climbingPriceComparisonData.setChildren(list);
            } else if (null != list && list.size() > 6) {
                climbingPriceComparisonData.setChildren(getRandomElements(list, 6));
            } else {
                climbingPriceComparisonData.setChildren(null);
            }
        }
        return resultList;
    }


    public static <T> T getRandomElement(List<T> list) {
        if (list == null || list.isEmpty()) {
            return null;
        }
        Random random = new Random();
        int index = random.nextInt(list.size());
        return list.get(index);
    }


    @Override
    public Object buildCategoryTree() {
        QueryWrapper<ClimbingPriceComparisonData> wrapper = new QueryWrapper<>();
        wrapper.select("category_id,pid,title");
        wrapper.orderByDesc("create_time");
        List<ClimbingPriceComparisonData> list = mapper.selectList(wrapper);
        ArrayList<TreeNode> treeNodes = new ArrayList<>();
        BeanUtils.copyBeanProp(list, treeNodes);
//        TreeNode root = buildTree(list);
        return treeNodes;
    }


    public static <T> List<T> getRandomElements(List<T> list, int count) {
        List<T> selected = new ArrayList<>();
        if (list.size() <= count) {
            return new ArrayList<>(list); // 如果请求的元素数量大于或等于列表大小，返回整个列表
        }
        Random random = new Random();
        while (selected.size() < count) {
            int index = random.nextInt(list.size());
            selected.add(list.get(index));
        }
        return selected;
    }


    private void SetChildren(List<ClimbingPriceComparisonData> categories, List<ClimbingPriceComparisonData> children) {
        for (ClimbingPriceComparisonData category : categories) {
            if (category.getChildren() != null) {
                SetChildren(category.getChildren(), children);
            }
            if (category.getPid() == 0) { // Assuming 0 is the root level
                children.add(category);
            }
        }
    }

    private void BuildChildrenUtil(ClimbingPriceComparisonData parent, Map<Integer, List<ClimbingPriceComparisonData>> childrenMap) {
        List<ClimbingPriceComparisonData> children = childrenMap.get(parent.getId());
        if (children != null) {
            parent.setChildren(children);
            children.forEach(child -> BuildChildrenUtil(child, childrenMap));
        }
    }

}
